package cn.com.callback

import cn.com.elite.EliteBean
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONObject;
/**
 *
 * @Title: aipHSTtest1229
 * @Description:华盛证券 测试  --内部接口
 * @author: chieh
 * @date 2022-12-20 10:28:00
 *
 */

public class aipHSTtest1229 implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTtest1229.class);
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();

        log.debug("getMethod:" + getMethod);
        long endTime ;
        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        try {
			String aaa="{\"weight_json\":[{\"qzId\":\"IB0001\",\"qzName\":\"客服\",\"proportion\":\"30\"},{\"qzId\":\"TEAM01\",\"qzName\":\"服务顾问\",\"proportion\":\"50\"},{\"qzId\":\"WM92BU\",\"qzName\":\"非主流一组\",\"proportion\":\"20\"}]}";
			log.debug("StringToJson=>"+aaa);
			
			JSONObject inObject = new JSONObject(aaa);
			log.debug("inObject=>"+inObject);
			
			String weight_json = GetJV(inObject, "weight_json");
			log.debug("weight_json=>"+weight_json);
			
			JSONArray arrJsonArray = new JSONArray(weight_json);
			int arrInt = arrJsonArray.length();
			
			log.debug("接入List数量:" + arrInt);	
			
			for (int i = 0; i < arrInt; i++) {
				
				JSONObject arrJson = arrJsonArray.getJSONObject(i);
				//获取信息
				String qzId = GetJV(arrJson, "qzId");
				String qzName = GetJV(arrJson, "qzName");
				String proportion = GetJV(arrJson, "proportion");
				log.debug("接入qzId:" + qzId);
				log.debug("接入qzName:" + qzName);
				log.debug("接入proportion:" + proportion);
				
			}
            outData = "{\"resultcode\":\"1\",\"resultmessage\":\"处理成功\"}";
        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        //log.debug("更新 信息完成返回结果:" + outData);

        return outData;
    }
// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		System.out.println("解析-k=" + getKey + " v=" + Rev_Value);
		return Rev_Value;
	}
    
    public static Map<String, Object> analysis(EliteBean eliteBean,JSONObject jsonObject,String PAGEID){
    //public static Map<String, Object> analysis(JSONObject jsonObject){
        Map<String, Object> result = new HashMap<>();
        Set<String> keys = jsonObject.keySet();
        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            Object value = jsonObject.get(key);
            if (value instanceof JSONObject) {
                JSONObject valueJsonObject = (JSONObject) value;
                //result.putAll(analysis(valueJsonObject));
                result.putAll(analysis(eliteBean,valueJsonObject,PAGEID));
            } else if (value instanceof JSONArray) {
                JSONArray jsonArray = (JSONArray) value;
                if (jsonArray.size() == 0) {
                    break;
                }
                //analysisJSONArray(jsonArray, result);
                analysisJSONArray(eliteBean,jsonArray, result,PAGEID);
            } else {
                result.put(key, value);
                //log.debug(key+":"+ value);
                def dataresult = eliteBean.update("insert into aipHSTtest1229( PAGEID, key1, value1) VALUES('" + PAGEID + "','" + key + "','" + value + "')", "dataSource");
                //log.debug("dataresult:" + dataresult);
            }
        }
        return result;
    }

    /**
     递归解析JSONArray
     @param jsonArray
     @param map
     */
    /*
   public static void analysisJSONAray(JSONArray jsonArray,Map<String,Object>map) {
       jsonArray.parallelStream().forEach(json->{
       Iterator<String> iterator = keys.iterator();
       while (iterator.hasNext()) {
           String json = iterator.next();
           if(json instanceof JSONObject){
               JSONObject valueJsonObject = (JSONObject) json;
               map.putAll(analysis(valueJsonObject));
           }else if(json instanceof JSONArray){
               JSONArray tmpJsonArray = (JSONArray)json;
               if(tmpJsonArray.size() == 0){
                   return;
               }
               analysisJSONAray(tmpJsonArray,map);
           }
       });
   }
   */
    public static void analysisJSONArray(EliteBean eliteBean,JSONArray jsonArray, Map<String, Object> map,String PAGEID) {
        Iterator<Object> iterator = jsonArray.iterator();
        while (iterator.hasNext()){
            Object json = iterator.next();
            if (json instanceof JSONObject) {
                JSONObject valueJsonObject = (JSONObject) json;
                //map.putAll(analysis(valueJsonObject));
                map.putAll(analysis(eliteBean,valueJsonObject,PAGEID));
            } else if (json instanceof JSONArray) {
                JSONArray tmpJsonArray = (JSONArray) json;
                if (tmpJsonArray.size() == 0) {
                    break;
                }
                analysisJSONArray(eliteBean,tmpJsonArray, map,PAGEID);
            }
        }
    }

}
